﻿CREATE PROCEDURE [dbo].[Security_ChangePassword]
-- --------------------------------------------------------------------------------- 
-- Procedure Name:  Security_ChangePassword
--
-- Description: Changes the users password
--
--
--
-- Version  Date          Author           Description
-- ---------------------------------------------------------------------------------
--  1       26-Aug-2012   The Collective   Created procedure
--
--
--
-- ---------------------------------------------------------------------------------
-- ---------------------------------------------------------------------------------
(@username varchar(255), 	  
 @oldpasswordencrypt varchar(255),
 @newpasswordencrypt varchar(255),
 @returncode as int output,
 @returnmessage as varchar(200) output)
AS
BEGIN
   SET NOCOUNT ON;
    
	-- Declarations
	Declare @recordcount as int;
	Declare @currentpasswordencrypt as varchar(255);

    -- Initialise variables
    Set @returncode = 0;
    Set @returnmessage = '';
	Set @recordcount = 0;

	-- Make sure the old and new passwords are different
	Select @currentpasswordencrypt = passwordencrypt from Accounts_User where username = @username;

	if @currentpasswordencrypt = @newpasswordencrypt 
	Begin
          -- Exit if user does not have permission
          Set @returncode = 1;
          Set @returnmessage = 'New password must be different from the current password';
	      Return 1;
    End;

	if @oldpasswordencrypt <> @currentpasswordencrypt 
	Begin
          -- Exit if user does not have permission
          Set @returncode = 1;
          Set @returnmessage = 'Current password incorrect.';
	      Return 1;
    End;
    
    
	Begin Transaction change_password_transaction;        
    -- Update the password
	Update Accounts_User set passwordencrypt = @newpasswordencrypt, password_lastchanged = GETDATE() where username = @username;  

	-- Assign number of rows affected to the record counter
	set @recordcount =  @@rowcount;

	if @recordcount = 1 
	begin
	    -- Commit
        Commit Transaction change_password_transaction;
	    Set @returncode = 0;
        Set @returnmessage = 'Successfully changed password.';    
    end;
	else
	begin
	    -- Rollback
        Rollback Transaction change_password_transaction;        
        Set @returncode = 1;
        Set @returnmessage = 'Unknown database error occurred.'; 
		Return 1; 
	end;
	    
      
    set nocount off
    
    Return 0;   

END;

